﻿using System.ComponentModel;
using System.Windows;
using Central.PumpService;

namespace Central
{
    public partial class PumpOverview
    {
        private readonly Window _parentWindow;
        private readonly CentralTerminalServiceClient _proxy;
        private readonly PumpStationDTO _pumpstationDTO;
        private PumpDTO[] _pumpDTOs;
        private readonly string[] _waterlevels = {"Lav", "Normal", "Høj", "Kritisk"};

        public PumpOverview(Window parentWindow, CentralTerminalServiceClient proxy, PumpStationDTO pumpStationDTO, CentralTerminalCallback callback)
        {
            InitializeComponent();

            _parentWindow = parentWindow;
            _proxy = proxy;
            _pumpstationDTO = pumpStationDTO;
            callback.OnWaterlevelChangedHandler = OnWaterlevelChanged;
            _proxy.Subscribe(2000, pumpStationDTO.Id);

            TextBlockIdentifier.Text = "Id: " + pumpStationDTO.Id + ", IP Addresse: " + pumpStationDTO.IPAddress + ", Port: " +
                                pumpStationDTO.Port;

            OnWaterlevelChanged(pumpStationDTO.Id, pumpStationDTO.Waterlevel);

            var worker = new BackgroundWorker();
            worker.DoWork += WorkerDoWork;
            worker.RunWorkerCompleted += WorkerOnRunWorkerCompleted;
            worker.RunWorkerAsync();
        }

        private void OnWaterlevelChanged(int stationId, int waterlevel)
        {
            TextBlockWaterlevel.Text = "Vandstand: " + _waterlevels[waterlevel];
        }

        private void WorkerDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            _pumpDTOs = _proxy.GetPumps(_pumpstationDTO.Id);
        }

        private void WorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
        {
            for (var i = 0; i < _pumpDTOs.Length; i++)
            {
                var pumpDTO = _pumpDTOs[i];
                var pump = new UcPump(i, pumpDTO);
                pump.Started += BtnStart_Click;
                pump.Stopped += BtnStop_Click;
                PumpsControl.Add(pump);
            }
        }

        private void BtnStart_Click(int pumpIndex)
        {
            _proxy.StartPump(_pumpstationDTO.Id, pumpIndex);
        }

        private void BtnStop_Click(int pumpIndex)
        {
            _proxy.StopPump(_pumpstationDTO.Id, pumpIndex);
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            _parentWindow.Show();
            _proxy.Unsubscribe(2000, _pumpstationDTO.Id);
        }
    }
}
